package com.luoyuanxiangvip.admin.core.filter;

import com.alibaba.fastjson.JSONObject;
import com.luoyuanxiangvip.common.utils.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 是否携带token访问
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/5/27 9:49
 */
public class AccessFilter extends AccessControlFilter {

    private static final String AUTHORIZATION_HEADER = "Authorization";


    /**
     * 可以发现他是调用的isAccessAllowed方法和onAccessDenied方法，只要两者有一个可以就可以了，
     * 从名字中我们也可以理解，他的逻辑是这样：
     * 先调用isAccessAllowed，如果返回的是true，
     * 则直接放行执行后面的filter和servlet，如果返回的是false，
     * 则继续执行后面的onAccessDenied方法，
     * 如果后面返回的是true则也可以有权限继续执行后面的filter和servelt。
     * 只有两个函数都返回false才会阻止后面的filter和servlet的执行。
     * @param request request
     * @param response response
     * @param mappedValue mappedValue
     * @return boolean
     * @throws Exception Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(AUTHORIZATION_HEADER);
        // 如果没有token 那么就不能访问资源 返回false 后面的调用方法不执行
        return StringUtils.isNotEmpty(authorization);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Credentials","true");
        res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS");
        res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
        res.setCharacterEncoding("UTF-8");
        res.getWriter().println(JSONObject.toJSONString(AjaxResult.error(50008,"token无效")));
        return false;
    }
}
